package com.lp.multi.juc.collection.unsafe;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.TimeUnit;

/**
 * @author: lp
 * @create: 2021-06-27 15:32
 * @description: HashSet并发不安全测试
 * 安全策略:
 * 1.Collections.synchronizedSet()
 * 2.CopyOnWriteArraySet
 */
public class SetTest {
    public static void main(String[] args) throws InterruptedException {
        Set<String> set = new HashSet<String>();
        for (int i = 0; i < 1000; i++) {
            new Thread(()->{
                set.add(UUID.randomUUID().toString().substring(0,5));
                System.out.println(set);
            },String.valueOf(i)).start();
        }

        TimeUnit.SECONDS.sleep(5);
        System.out.println(set.size());
    }
}

/**
 * Collections.synchronizedSet
 */
class SafeCollectsSetTest{
    public static void main(String[] args) throws InterruptedException {
        Set<String> set = Collections.synchronizedSet(new HashSet<String>());
        for (int i = 0; i < 1000; i++) {
            new Thread(()->{
                set.add(UUID.randomUUID().toString().substring(0,5));
                System.out.println(set);
            },String.valueOf(i)).start();
        }

        TimeUnit.SECONDS.sleep(5);
        System.out.println(set.size());
    }
}

class SafeCopyOnWriteListSetTest{
    public static void main(String[] args) throws InterruptedException {
        Set<String> set = new CopyOnWriteArraySet<>();
        for (int i = 0; i < 1000; i++) {
            new Thread(()->{
                set.add(UUID.randomUUID().toString().substring(0,5));
                System.out.println(set);
            },String.valueOf(i)).start();
        }

        TimeUnit.SECONDS.sleep(5);
        System.out.println(set.size());
    }
}
